package util

import (
	"crypto/tls"
	"fmt"
	"gitee.com/gopher2011/gva/server/dao"
	"github.com/jordan-wright/email" // 电子邮件库 https://segmentfault.com/a/1190000021761747?utm_source=tag-newest
	"net/smtp"
	"strings"
)

// 发送邮件 参数<to>表示该邮件发送去哪里, <subject>邮件的标题,<body>邮件的内容
func send(to []string, subject string, body string) error {
	from := dao.Cfg.Email.From
	nickname := dao.Cfg.Email.Nickname
	secret := dao.Cfg.Email.Secret
	host := dao.Cfg.Email.Host
	port := dao.Cfg.Email.Port
	isSSL := dao.Cfg.Email.IsSSL

	auth := smtp.PlainAuth("", from, secret, host)
	e := email.NewEmail()
	if nickname != "" { //初始化邮件的发送者
		e.From = fmt.Sprintf("%s <%s>", nickname, from)
	} else {
		e.From = from
	}
	e.To = to
	e.Subject = subject
	e.HTML = []byte(body)
	var err error
	hostAddr := fmt.Sprintf("%s:%d", host, port) //接收邮件的主机地址
	if isSSL {
		err = e.SendWithTLS(hostAddr, auth, &tls.Config{ServerName: host})
	} else {
		err = e.Send(hostAddr, auth)
	}
	return err
}

// 将错误发送到指定邮箱
func Error2Email(subject, body string) error {
	to := strings.Split(dao.Cfg.Email.To, ",")
	if to[len(to)-1] == "" { // 判断切片的最后一个元素是否为空,为空则移除
		to = to[:len(to)-1] // 0==>到最后一个元素,不包括最后一个元素
	}
	return send(to, subject, body)
}
